package de.mhus.lib.mandala.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.servlets.DefaultServlet;

import de.mhus.lib.core.MString;
import de.mhus.lib.mandala.Ui;
import de.mhus.lib.mandala.UiControl;
import de.mhus.lib.mandala.Window;
import de.mhus.lib.mandala.bind.RemoteRegistry;

public class MandalaServlet extends DefaultServlet {

	private static final long serialVersionUID = 1L;

	@Override
	public void service(HttpServletRequest arg0, HttpServletResponse arg1)
			throws ServletException, IOException {
		
		if (arg0.getParameter("_mandala_action") != null) {
			doCallback(arg0, arg1);
			return;
		}
		
		super.service(arg0, arg1);
	}




	private void doCallback(HttpServletRequest request, HttpServletResponse response) {
		
		String action = request.getParameter("_mandala_action");
		String windowId = MString.beforeIndex(action, '.');
		String remoteId = MString.afterIndex(action, '.');
		String requestId = request.getParameter("_mandala_request_id");
		
		Ui ui = getUi(request);
		
		if (ui.isDebugRemoteCalls())
			System.out.println("callback: " + action + " " + requestId + " " + request.getParameter("data"));
		Window window = ui.getWindow(windowId);
		if (window == null) {
			return;
		}
		
		RemoteRegistry remote = window.getRemote(remoteId);
		if (remote == null) {
			return;
		}
		
		remote.doRemoteCall(request, response, requestId);
	}




	public static Ui getUi(HttpServletRequest req) {
		Ui ui = (Ui)req.getSession().getAttribute("__mandala_ui");
		if (ui != null && "1".equals(req.getParameter("_reset")) ) {
			ui.close();
			ui = null;
		}
		if (ui == null) {
			ui = UiControl.getInstance().getUi();
			ui.setWebPath(req.getRequestURI());
			req.getSession().setAttribute("__mandala_ui", ui);
		}
		return ui;
	}
	
	public static Window getWindow(HttpServletRequest req, String id) {
		
		Ui ui = getUi(req);
		Window window = ui.getWindow(id);
		if (window == null) {
			return null;
		}
		return window;
	}
	
	
}
